package com.stox.manager.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.stox.manager.CountryManager;
import com.stox.manager.ExchangeManager;
import com.stox.manager.ScripManager;
import com.stox.model.Country;
import com.stox.model.Exchange;
import com.stox.model.Scrip;
import com.stox.repository.ScripRepository;

@Component
@Transactional
public class ScripManagerImpl implements ScripManager {
	
	@Autowired
	private ScripRepository scripRepository;
	
	@Autowired
	private CacheManager cacheManager;
	
	@Autowired
	private CountryManager countryManager;
	
	@Autowired
	private ExchangeManager exchangeManager;

	@Override
	@CachePut(value=cacheName, key="#scrip.id")
	public Scrip saveAndFlush(Scrip scrip) {
		return scripRepository.saveAndFlush(scrip);
	}
	
	@Override
	@Cacheable(value=cacheName, key="'exchange-'+#exchangeId")
	public List<Scrip> findByExchangeId(Long exchangeId) {
		return scripRepository.findByExchangeIdAndActive(exchangeId, Boolean.TRUE);
	}

	@Override
	@Cacheable(cacheName)
	@SuppressWarnings("unchecked")
	public Scrip findOne(Long id) {
		Cache cache = cacheManager.getCache(cacheName);
		if(null != cache){
			for(Country country : countryManager.findAll()){
				for(Exchange exchange : exchangeManager.findByCountryId(country.getId())){
					ValueWrapper wrapper = cache.get("exchange-"+exchange.getId());
					if(null != wrapper && null != wrapper.get()){
						List<Scrip> scrips = (List<Scrip>)wrapper.get();
						for(Scrip scrip : scrips){
							if(scrip.getId().equals(id)){
								return scrip;
							}
						}
					}
				}
			}
		}
		return scripRepository.findOne(id);
	}
	
	@Transactional
	@CachePut(value=cacheName, key="#scrip.id")
	public Scrip save(Scrip scrip) {
		return scripRepository.save(scrip);
	}

}
